package com.liumingtai.demo01.upload.utils;


import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.PutObjectRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.InputStream;

/**
 * Created by
 *
 * @author Honey
 */
@Component
@Slf4j
public class OssUtils {

    @Value("${aliyun.oss.ENDPOINT}")
    private String endpoint;

    @Value("${aliyun.oss.ACCESS_KEY_ID}")
    private String accessKeyId;

    @Value("${aliyun.oss.ACCESS_KEY_SECRET}")
    private String accessKeySecret;

    @Value("${aliyun.oss.BUCKET_NAME}")
    private String bucketName;

    @Value("${aliyun.oss.ACCESS_URL}")
    private String domain;

    private OssUtils(){
    }

    private static class OSSUtilInner{
        private static OssUtils instance=  new OssUtils();
    }

    public static OssUtils getInstance(){
        return OssUtils.OSSUtilInner.instance;
    }


    public  String upload(String fileName, InputStream inputStream) {
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, fileName, inputStream);
        ossClient.putObject(putObjectRequest);
        ossClient.shutdown();
        log.info("OSS上传文件:" + fileName);
        return domain + fileName;
    }

    public  void downLoad(String fileName,String objectName){
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        // 下载OSS文件到本地文件。如果指定的本地文件存在会覆盖，不存在则新建。
        ossClient.getObject(new GetObjectRequest(bucketName,objectName), new File(fileName));
        // 关闭OSSClient。
        ossClient.shutdown();
    }

}
